/**
 * edurender
 * test_window.c
 * (c) 2009 J. Brad Byrd
 */

#include <edurender/er.h>

#define STRICT
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <windowsx.h>

#include <assert.h>

#pragma warning(disable : 4100) // No "unreferenced formal parameter" warnings in this file.

#define WINDOW_CLASS "Edurender Test Window"

static void OnSize(HWND hwnd, UINT state, int cx, int cy)
{

}

static BOOL OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
{
	return TRUE;
}

static void OnDestroy(HWND hwnd)
{
	PostQuitMessage(0);
}

static void OnPaint(HWND hwnd)
{
	PAINTSTRUCT ps;
	BeginPaint(hwnd, &ps);

	EndPaint(hwnd, &ps);
}

static LRESULT CALLBACK WndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uiMsg)
	{
		HANDLE_MSG(hwnd, WM_CREATE, OnCreate);
		HANDLE_MSG(hwnd, WM_SIZE, OnSize);
		HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy);
		HANDLE_MSG(hwnd, WM_PAINT, OnPaint);
	}

	return DefWindowProc(hwnd, uiMsg, wParam, lParam);
}

void testCreateWindowAndContext(const char *windowTitle, ERuint width, ERuint height, ERContext *context)
{
	WNDCLASS wc;
	HWND hwnd;
	RECT rect;
	int winWidth;
	int winHeight;

	rect.left = 0;
	rect.top = 0;
	rect.right = width;
	rect.bottom = height;

	AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
	
	winWidth = rect.right - rect.left;
	winHeight = rect.bottom - rect.top;
	
	wc.style = 0;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	/**
	 * This won't work if this is ever in a .dll, see:
	 * http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
	 */
	wc.hInstance = (HINSTANCE)GetModuleHandle(NULL);
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = GetStockBrush(WHITE_BRUSH);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = WINDOW_CLASS;

	if (!RegisterClass(&wc))
		assert(0);

	hwnd = CreateWindow(
		WINDOW_CLASS,                   /* Class Name */
		(LPCTSTR)windowTitle,           /* Title */
		WS_OVERLAPPEDWINDOW,            /* Style */
		CW_USEDEFAULT, CW_USEDEFAULT,   /* Position */
		winWidth, winHeight,            /* Size */
		NULL,                           /* Parent */
		NULL,                           /* No menu */
		wc.hInstance,                   /* Instance */
		0);                             /* No special parameters */

	assert(hwnd != INVALID_HANDLE_VALUE);

	ShowWindow(hwnd, SW_SHOW);
			
	if (erCreateContext(width, height, hwnd, context) != ER_RESULT_OK)
		assert(0);
}

ERbool testPumpWindow(ERContext context)
{
	MSG msg;

	ZeroMemory(&msg, sizeof(msg));

	while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		if (msg.message == WM_QUIT)
		{
			return ER_FALSE;
		}
		else
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	
	return ER_TRUE;
}
